package top.aiprogram.login.controller;

import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.aiprogram.common.utils.SecurityUtils;
import top.aiprogram.user.entity.User;
import top.aiprogram.user.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by HP on 2018/10/15.
 */
@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService userService;
/**
*@Author JackQi {www.coder520.com}
*@Date 2018/10/15 15:30
*@Description 进入登录页面
*/

    @RequestMapping("login")
    public String login(){

        return "login";
    }
    /**
    *@Author JackQi {www.coder520.com}
    *@Date 2018/10/15 15:30
    *@Description 校验登录
    */
    //这里也可以在参数中传入session,实际上,通过request也可以获取到,所以就没必要传session了
    @RequestMapping("check")
    @ResponseBody
    public String checklogin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String username = httpServletRequest.getParameter("username");
        String inputPassword = httpServletRequest.getParameter("password");
        //查数据库,如果查到数据,调用MD5密码加密进行校验
       User user= userService.findUserByName(username);
       if (user==null){
           return "login_fail";
       }
        String dbPassword= user.getPassword();
        boolean b = SecurityUtils.checkPassword( inputPassword,dbPassword);
//        httpServletResponse.setContentType("application/json;charset=utf-8");
        //校验成功
        //获取session存用户信息,返回成功的signal
        //校验失败
        //返回校验失败的signal
        if (b){
            httpServletRequest.getSession().setAttribute("userinfo",user);
            return "login_success";
        }else {
            return "login_fail";
        }
    }
    /**
    *@Author JackQi {www.coder520.com}
    *@Date 2018/10/15 15:37
    *@Description 创建用户,注册用户;本来考勤系统是不需要注册这个操作的,但是需要用户
     * 所以创建这个方法,用来往数据库中添加用户,可以通过postman进行发送post请求,这样的话
     * 就不用再单独配置一个页面进行用户的插入操作了.
    */
    @RequestMapping("register")
    @ResponseBody
    public void register(@RequestBody User user,HttpServletResponse httpServletResponse){
        user.setPassword(SecurityUtils.encrypt(user.getPassword()));
        int i = userService.creatUser(user);
        System.out.println(i);
        httpServletResponse.setContentType("application/json;charset=utf-8");
    }
}
